const execFile = require("child_process").execFile;
const os = require("os");
const fs = require("fs-extra");
const path = require("path")
const Grib2ToJson = async (_path, options) => {
  const grib2jsonCommand = path.resolve(
    __dirname,`bin/${os.platform() === "win32" ? "grib2json.cmd" : "grib2json"}`
  );

  return new Promise((resolve, rejects) => {
    execFile(
      `${grib2jsonCommand}`,
      ["-d", "-o", options.output, "-n", "-c", _path],
      {
        maxBuffer: 8 * 1024 * 1024,
      },
      function (err, stdout) {
        if (err) {
          console.log(err);
          rejects(err);
          return;
        }
        if (options.output) {
          fs.readJson(options.output, function (err, json) {
            if (err) {
              console.log(err);
              rejects(err);
              return;
            }
            console.log(`转换[${_path}]文件成json成功`);

            return resolve(json);
          });
        } else {
          let json = JSON.parse(stdout);
          console.log(`转换[${_path}]文件成json成功`);

          return resolve(json);
        }
      }
    );
  });
};

module.exports = {
  Grib2ToJson,
};
